import 'dart:convert';

import 'package:bxultimate/app/router/router_name.dart';
import 'package:bxultimate/data/request/organization_request.dart';
import 'package:bxultimate/domain/application/organization/OrganizationAnnouncementTemplateCreateDto.dart';
import 'package:bxultimate/domain/application/organization/OrganizationAnnouncementTemplateDto.dart';
import 'package:bxultimate/domain/common/app_single_option.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/src/components/cell/td_cell.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import 'state.dart';

class OrganizationStatisticsTaskCreateController extends GetxController {
  final OrganizationStatisticsTaskCreateState state =
      OrganizationStatisticsTaskCreateState();

  TextEditingController titleController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();

  TextEditingController placeholderController = TextEditingController();
  TextEditingController placeholderTwoController = TextEditingController();
  TextEditingController radioTextController = TextEditingController();

  // 当前是编辑还是删除，   编辑是对应的索引    新增是-1
  var currentEditIndex = -1;

  var radioList = [
    AppSingleOption(label: '年-月-日 时:分', value: "1"),
    AppSingleOption(label: '年-月-日', value: "2"),
    AppSingleOption(label: '时:分', value: "3"),
  ];

  var chatRoomId = Get.arguments['chatRoomId'];
  var attributionCode = Get.arguments['attributionCode'];
  var attributionTargetId = Get.arguments['attributionTargetId'];

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

  }

  // 必填选填切换
  bool requiredChange(bool value) {
    state.requiredSelected = value;
    return value;
  }

  void addFromItem(index) {
    OrganizationAnnouncementTemplateCreateDto dto =
        OrganizationAnnouncementTemplateCreateDto();

    if (placeholderController.text == '') {
      SmartDialog.showNotify(msg: '请输入标题', notifyType: NotifyType.failure);
      return;
    }
    // 文本和数字
    if (index == 0 || index == 1) {
      dto = dto.copyWith(
          placeholder: placeholderController.text,
          placeholderTwo: placeholderTwoController.text,
          textInput: placeholderController.text,
          textinputplaceholder: placeholderTwoController.text,
          required: state.requiredSelected,
          type: index + 1);
    }
    // 日期
    if (index == 2) {
      Attributes attributes = Attributes();
      List<TimeList> timeList = [
        TimeList(time: '年-月-日 时:分', icon: 'tn-icon-success', type: 1),
        TimeList(time: '年-月-日', icon: 'tn-icon-success', type: 2),
        TimeList(time: '时:分', icon: 'tn-icon-success', type: 3),
      ];
      print('selectDate: ${state.selectDate}');
      attributes = attributes.copyWith(
          timeindex: int.parse(state.selectDate), timeList: timeList);
      dto = dto.copyWith(
          placeholder: placeholderController.text,
          placeholderTwo: placeholderTwoController.text,
          textInput: placeholderController.text,
          textinputplaceholder: placeholderTwoController.text,
          required: state.requiredSelected,
          type: index + 1,
          attributes: attributes);
    }

    if (currentEditIndex == -1) {
      state.formItem.add(dto);
    } else {
      state.formItem[currentEditIndex] = dto;
    }
    update();
    Get.back();
  }

  // 删除
  void removeFormItem(index) async {
    state.formItem.removeAt(index);
    update();
  }

  void dateChange(String? selectedId) {
    state.selectDate = selectedId!;
  }

  addRadioForm(OrganizationAnnouncementTemplateCreateDto p1) {
    if (currentEditIndex == -1) {
      state.formItem.add(p1);
    } else {
      state.formItem[currentEditIndex] = p1;
    }
    update();
    Get.back();
  }

  void create() async {
    if(titleController.text == ''){
      SmartDialog.showNotify(msg: '请填写任务名称', notifyType: NotifyType.failure);
      return;
    }
    if(descriptionController.text == ''){
      SmartDialog.showNotify(msg: '请填写任务描述', notifyType: NotifyType.failure);
      return;
    }
    if(state.idcardList.length == 0){
      SmartDialog.showNotify(msg: '请添加发送人员', notifyType: NotifyType.failure);
      return;
    }

    if(state.formItem.length == 0 ){
      SmartDialog.showNotify(msg: '请添加统计项', notifyType: NotifyType.failure);
      return;
    }


    showGeneralDialog(
      context: Get.context!,
      pageBuilder: (BuildContext buildContext, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return TDAlertDialog(
          title: '是否存储为模板',
          showCloseButton: true,
          rightBtnAction: (){
            createWithTemplate(1);
          },
          leftBtnAction: (){
            createWithTemplate(0);
          },
        );
      },
    );

  }

  void createWithTemplate(int saveTemplate)async{
    await OrganizationRequest.insertStatisticsTask({
      "title": titleController.text,
      "description":descriptionController.text,
      "idcardList": state.idcardList,
      "chatRoomId": chatRoomId,
      "attributionCode": attributionCode,
      "attributionTargetId": attributionTargetId,
      "templateContent": state.formItem,
      "info": json.encode(state.formItem),
      "isTemplate":saveTemplate
    });
    SmartDialog.showNotify(msg: '操作成功', notifyType: NotifyType.success);
    Get.back();
    Get.back();

  }

  void toSelectUser(TDCell cell) async {
    state.idcardList = await Get.toNamed(RouterName.organizationSelectUser,
        arguments: Get.arguments['teamId']);
  }

  void templateSelect() async {
    List<OrganizationAnnouncementTemplateDto> dtoList =
        await OrganizationRequest.getStatisticsTaskTeamplateList(1, 9999);

    List<String> selectList = dtoList.map((e) => e.templateName!).toList();

    //
    TDPicker.showMultiPicker(Get.context, title: '选择模板',
        onConfirm: (selected) {
          state.formItem.addAll(dtoList[selected[0]].content!);
          Navigator.of(Get.context!).pop();
          update();
        }, data: [selectList]);
  }
}
